import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import store from '../store'
import Home from '@/views/Home.vue'
import Activities from '@/views/Activities.vue'
import Teams from '@/views/Teams.vue'
import TeamDetail from '@/views/TeamDetail.vue'
import News from '@/views/News.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/news',
    name: 'News',
    component: News
  },
  {
    path: '/activities',
    name: 'Activities',
    component: () => import('../views/Activities.vue')
  },
  {
    path: '/activities/:id',
    name: 'ActivityDetail',
    component: () => import('../views/ActivityDetail.vue'),
    props: true
  },
  {
    path: '/teams',
    name: 'Teams',
    component: Teams
  },
  {
    path: '/teams/:id',
    name: 'TeamDetail',
    component: TeamDetail,
    props: true
  },
  {
    path: '/education',
    name: 'Education',
    component: () => import('../views/Education.vue')
  },
  {
    path: '/donation',
    name: 'Donation',
    component: () => import('../views/Donation.vue')
  },
  {
    path: '/donation/:id',
    name: 'DonationDetail',
    component: () => import('../views/DonationDetail.vue'),
    props: true
  },
  {
    path: '/game',
    name: 'Game',
    component: () => import('../views/Game.vue')
  },
  {
    path: '/announcements',
    name: 'Announcements',
    component: () => import('../views/Announcements.vue')
  },
  {
    path: '/announcements/:id',
    name: 'AnnouncementDetail',
    component: () => import('../views/AnnouncementDetail.vue'),
    props: true
  },
  // 管理员路由
  {
    path: '/admin',
    component: () => import('@/views/admin/Layout.vue'),
    redirect: '/admin/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('@/views/admin/Dashboard.vue'),
        meta: { title: '工作台' }
      },
      {
        path: 'account',
        name: 'AdminAccount',
        component: () => import('@/views/admin/Account.vue'),
        meta: { title: '账户管理' }
      },
      {
        path: 'website',
        name: 'AdminWebsite',
        component: () => import('@/views/admin/Website.vue'),
        meta: { title: '网站管理' }
      },
      {
        path: 'hours',
        name: 'AdminHours',
        component: () => import('@/views/admin/Hours.vue'),
        meta: { title: '时长管理' }
      },
      {
        path: 'messages',
        name: 'AdminMessages',
        component: () => import('@/views/admin/Messages.vue'),
        meta: { title: '消息管理' }
      },
      {
        path: 'volunteers',
        name: 'AdminVolunteers',
        component: () => import('@/views/admin/Volunteers.vue'),
        meta: { title: '志愿者管理' }
      },
      {
        path: 'projects',
        name: 'AdminProjects',
        component: () => import('@/views/admin/Projects.vue'),
        meta: { title: '志愿项目管理' }
      },
      {
        path: 'teams',
        name: 'AdminTeams',
        component: () => import('@/views/admin/Teams.vue'),
        meta: { title: '志愿队伍管理' }
      },
      {
        path: 'config',
        name: 'AdminConfig',
        component: () => import('@/views/admin/Config.vue'),
        meta: { title: '配置管理' }
      }
    ]
  },
  // 志愿者路由
  {
    path: '/volunteer',
    name: 'Volunteer',
    component: () => import('../views/volunteer/Layout.vue'),
    meta: { requiresAuth: true, role: 'volunteer' },
    redirect: '/volunteer/home',
    children: [
      {
        path: 'home',
        name: 'VolunteerHome',
        component: () => import('../views/volunteer/Home.vue')
      },
      {
        path: 'profile',
        name: 'VolunteerProfile',
        component: () => import('../views/volunteer/Profile.vue')
      },
      {
        path: 'certificate',
        name: 'VolunteerCertificate',
        component: () => import('../views/volunteer/Certificate.vue')
      },
      {
        path: 'comments',
        name: 'VolunteerComments',
        component: () => import('../views/volunteer/Comments.vue')
      },
      {
        path: 'projects',
        name: 'VolunteerProjects',
        component: () => import('../views/volunteer/Projects.vue')
      },
      {
        path: 'projects/:id',
        name: 'VolunteerProjectDetail',
        component: () => import('../views/volunteer/ProjectDetail.vue'),
        props: true
      },
      {
        path: 'service-hours',
        name: 'VolunteerServiceHours',
        component: () => import('../views/volunteer/ServiceHours.vue')
      },
      {
        path: 'teams',
        name: 'VolunteerTeams',
        component: () => import('../views/volunteer/Teams.vue')
      }
    ]
  },
  // 组织路由
  {
    path: '/organization',
    name: 'Organization',
    component: () => import('../views/organization/Layout.vue'),
    meta: { requiresAuth: true, role: 'organization' },
    redirect: '/organization/home',
    children: [
      {
        path: 'home',
        name: 'OrganizationHome',
        component: () => import('../views/organization/Home.vue')
      },
      {
        path: 'hours',
        name: 'OrganizationHours',
        component: () => import('../views/organization/Hours.vue')
      },
      {
        path: 'members',
        name: 'OrganizationMembers',
        component: () => import('../views/organization/Members.vue')
      },
      {
        path: 'projects',
        name: 'OrganizationProjects',
        component: () => import('../views/organization/Projects.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 不需要登录就可以访问的路由
const publicRoutes = ['/login', '/register', '/forget-password', '/']

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果是公开路由，直接放行
  if (publicRoutes.includes(to.path)) {
    next()
    return
  }
  
  // 如果没有token，重定向到登录页
  if (!token) {
    ElMessage.warning('请先登录')
    next(`/login?redirect=${to.path}`)
    return
  }
  
  try {
    // 如果有token但没有用户信息，获取用户信息
    if (!store.state.user) {
      await store.dispatch('getUserInfo')
    }
    
    // 检查用户角色权限
    const userRole = store.state.user.role
    const requiredRole = to.meta.role
    
    // 如果路由需要特定角色
    if (requiredRole) {
      // 将路由要求的角色名称转换为对应的数字
      const roleMap = {
        'admin': 1,
        'volunteer': 2,
        'organization': 3,
        'user': 0
      }
      
      if (roleMap[requiredRole] !== userRole) {
        ElMessage.error('没有访问权限')
        next('/403')
        return
      }
    }
    
    next()
  } catch (error) {
    // 获取用户信息失败，可能是token过期
    localStorage.removeItem('token')
    ElMessage.error('登录已过期，请重新登录')
    next(`/login?redirect=${to.path}`)
  }
})

export default router 